import sys

from PyQt5 import QtCore,QtSql
from PyQt5.QtWidgets import QWidget, QLabel, QLineEdit, QPushButton, \
    QGridLayout, QVBoxLayout, QHBoxLayout, QMessageBox, QApplication
from views.signin_page import SigninPage


from controller.window_controller import *


class LoginPage(QWidget):
    switch_siginin_window = QtCore.pyqtSignal()
    switch_main_window = QtCore.pyqtSignal()

    def __init__(self):
        super(LoginPage, self).__init__()
        self.setWindowTitle('登录Hello Word')
        self.resize(300, 100)

        self.user_label = QLabel('用户名:', self)
        self.pwd_label = QLabel('密码:', self)
        self.user_line = QLineEdit(self)
        self.pwd_line = QLineEdit(self)
        self.login_button = QPushButton('登录', self)
        self.signin_button = QPushButton('注册', self)
        self.lineedit_init()
        self.pushbutton_init()
        # 网格布局QGridLayout当使用该布局管理器的时候，
        # 你可以把整个窗体想象成带有坐标的，然后只用把各个控件放在相应的坐标就好了，
        # 请看示例(还是上方的登录框)：
        self.grid_layout = QGridLayout()
        self.h_layout = QHBoxLayout()
        self.v_layout = QVBoxLayout()
        self.layout_init()

    def layout_init(self):

        self.grid_layout.addWidget(self.user_label, 0, 0, 1, 1)
        self.grid_layout.addWidget(self.user_line, 0, 1, 1, 1)
        self.grid_layout.addWidget(self.pwd_label, 1, 0, 1, 1)
        self.grid_layout.addWidget(self.pwd_line, 1, 1, 1, 1)
        self.h_layout.addWidget(self.signin_button)
        self.h_layout.addWidget(self.login_button)
        self.v_layout.addLayout(self.grid_layout)
        self.v_layout.addLayout(self.h_layout)

        self.setLayout(self.v_layout)

    def lineedit_init(self):
        self.user_line.setPlaceholderText('请输入用户名')
        self.pwd_line.setPlaceholderText('请输入密码')
        self.pwd_line.setEchoMode(QLineEdit.EchoMode.Password)

        self.user_line.textChanged.connect(self.check_input_func)
        self.pwd_line.textChanged.connect(self.check_input_func)

    def pushbutton_init(self):
        self.login_button.setEnabled(False)
        self.login_button.clicked.connect(self.check_login_func)
        self.signin_button.clicked.connect(self.go_signin)

    def check_login_func(self):

        if USER_PWD.get(self.user_line.text()) == self.pwd_line.text():
            QMessageBox.information(self, '通知', '登录成功')
            self.switch_main_window.emit()
        else:
            QMessageBox.critical(self, '错误', '账号或密码错误!')

        self.user_line.clear()
        self.pwd_line.clear()

    def go_signin(self):
        self.switch_siginin_window.emit()

    def check_input_func(self):
        if self.user_line.text() and self.pwd_line.text():
            self.login_button.setEnabled(True)
        else:
            self.login_button.setEnabled(False)


if __name__ == '__main__':
    app = QApplication(sys.argv)
    demo = LoginPage()
    demo.show()
    sys.exit(app.exec())
